package com.slfx.stock.dao;

import com.slfx.stock.pojo.Stock;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.common.Mapper;

public interface StockMapper extends Mapper<Stock> {

    @Select("select * from tb_stock  where goods_id=#{goodsId}")
    Stock selectByGoodsId(@Param("goodsId") String goodsId);

    /**
     * 悲观锁
     * @param goodsId
     * @return
     */
    @Select("select * from tb_stock  where goods_id=#{goodsId} for update")
    Stock selectByGoodsIdForUpdate(@Param("goodsId") String goodsId);

    /**
     * 这个方法并发是线程安全的，多次并发，最终的数据是正确的，但是库存会扣减到负数
     * @param goodsId
     * @param num
     * @return
     */
    @Update("update tb_stock set amount=amount-#{num} where goods_id=#{goodsId}")
    int lessInventory(@Param("goodsId") String goodsId,@Param("num") int num);

    /**
     * 基本版本号修改库存
     * @param goodsId
     * @param num
     * @param version
     * @return
     */
    @Update("update tb_stock set amount=amount-#{num},version=version+1 where goods_id=#{goodsId} and version=#{version}")
    int lessInventoryByVersion(@Param("goodsId") String goodsId,@Param("num") int num,@Param("version") int version);

    /**
     * 并发安全，并且库存不会扣减到负数
     * @param goodsId
     * @param num
     * @return
     */
    @Update("update tb_stock set amount=amount-#{num} where goods_id=#{goodsId} and amount-#{num}>=0")
    int lessInventoryByVersionOut(@Param("goodsId") String goodsId,@Param("num") int num);

    /**
     * 并发安全，并且库存不会扣减到负数
     * @param goodsId
     * @param num
     * @return
     */
    @Update("update tb_stock set amount=amount-#{num} where goods_id=#{goodsId} and amount>0")
    int lessInventoryByVersionOut2(@Param("goodsId") String goodsId,@Param("num") int num);

    /**
     * @param goodsId
     * @param num
     * @return
     */
    @Update("update tb_stock set amount=#{num} where goods_id=#{goodsId}")
    int lessInventoryGetAndSet(String goodsId, int num);
}
